package spider.impl.chapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import spider.NovelSiteEnum;
import spider.entitys.ChapterDetail;
import spider.impl.AbstractSpider;
import spider.interfaces.IChapterDetailSpider;
import spider.util.NovelSpiderUtil;

import java.util.Map;

/**
 * created by yb
 * on 2017/8/9.
 **/
public abstract class AbstractChapterDetailSpider extends AbstractSpider implements IChapterDetailSpider {
    @Override
    public ChapterDetail getChapterDetail(String url) {
        try {
            String result = craw(url,"chapter-detail-charset");
            result = result.replace("&nbsp;","  ");
            result = result.replace("<br />","${line}");
            result = result.replace("<br/>","${line}");
            Map<String, String> context = NovelSpiderUtil.getContext(NovelSiteEnum.getNovelSiteEnumByUrl(url));
            Document doc = Jsoup.parse(result,context.get("charset"));
            doc.setBaseUri(url);
            ChapterDetail detail = new ChapterDetail();
            String selector = context.get("chapter-detail-title-selector");
            detail.setTittle(doc.select(selector).text());
            selector = context.get("chapter-detail-content-selector");
            detail.setContent(doc.select(selector).text().replace("${line}","\n"));
            selector = context.get("chapter-detail-prev-selector");
            detail.setPrev(doc.select(selector).get(0).absUrl("href"));
            selector = context.get("chapter-detail-next-selector");
            detail.setNext(doc.select(selector).get(0).absUrl("href"));
            selector = context.get("chapter-detail-catalog-selector");
            detail.setCatalog(doc.select(selector).get(0).absUrl("href"));
            return detail;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
